package com.taotao.controller;

import com.taotao.config.WxMpConfiguration;
import com.taotao.config.WxMpProperties;
import com.taotao.entity.ServiceErrorDto;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangjin
 * @title: WechatTemplateController
 * @projectName sw-gateway
 * @description:
 * @date 2021/12/9 14:47
 */
@RestController
@Slf4j
public class WechatTemplateController {
    @Autowired
    private WxMpProperties wxMpProperties;
    @Value("${mayikt.errorTemplateId}")
    private String errorTemplateId;

    /*
    *{
      "ip":"192.168.110.1",
      "port":8080,
      "serviceName":"mayikt-member",
      "errorMsg":"null",
      "errorTime":"2021-11-23 00:16:47",
      "openId":"ommED6cuwHYsgnT5WcamQhf2zJio"

    }
     */
    @RequestMapping("sendWechatTemplateError")
    public String sendWechatTemplateError(@RequestBody ServiceErrorDto serviceErrorDto) {
        WxMpTemplateMsgService wxMpTemplateMsgService = WxMpConfiguration.getMpServices().get(wxMpProperties.getConfigs().get(0).getAppId()).getTemplateMsgService();
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.setTemplateId(errorTemplateId);
        wxMpTemplateMessage.setToUser(serviceErrorDto.getOpenId());
        List<WxMpTemplateData> data = new ArrayList<>();
        data.add(new WxMpTemplateData("first", serviceErrorDto.getServiceName()));
        data.add(new WxMpTemplateData("keyword1", serviceErrorDto.getIp() + ":" + serviceErrorDto.getPort()));
        data.add(new WxMpTemplateData("keyword2", serviceErrorDto.getErrorMsg()));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(serviceErrorDto.getErrorTime());
        data.add(new WxMpTemplateData("keyword3", format));
        wxMpTemplateMessage.setData(data);
        wxMpTemplateMessage.setUrl("http://www.mayikt.com");
        try {
            wxMpTemplateMsgService.sendTemplateMsg(wxMpTemplateMessage);
        } catch (Exception e) {
            log.error("<e:>", e);
        }
        return "ok";
    }


}
